package tr.muyat.accelerometer.visualizer;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.nio.ByteBuffer;

/**
 * 
 * @author fxulusoy
 */
public class ConnectionHandler implements Runnable {

	private static final int EXIT_CMD = -1;
	
	private Chart chart;
	
	private Socket socket;

	/**
	 * The constructor.
	 * 
	 * @param socket
	 */
	public ConnectionHandler(Socket socket, Chart chart) {
		this.chart = chart;
		this.socket = socket;
	}

	public void run() {
		try {
			// Reads client's message
			InputStream inputStream = socket.getInputStream();
			byte[] buffer = new byte[1024];
			
			while (true) {
				System.out.println("waiting for input");
				int length = inputStream.read(buffer);

				if (length == EXIT_CMD) {
					System.out.println("finish process");
					break;
				}
				processInput(buffer, length);
				System.out.println("input was received");
				System.out.println("-----------------");
			}

			inputStream.close();
			socket.close();
			chart.remove();
			chart = null;
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	private void processInput(byte[] buffer, int length) {
		
		float[] values = new float[3];
		ByteBuffer buf = ByteBuffer.wrap(buffer, 0, length);
		for (int i = 0; i < length / 4; i++) {
			float float1 = buf.getFloat();
			switch (i) {
			case 0:
				values[0] = float1;
				System.out.println("X-value: " + float1);
				break;
			case 1:
				values[1] = float1;
				System.out.println("Y-value: " + float1);
				break;
			case 2:
				values[2] = float1;
				System.out.println("Z-value: " + float1);
				break;				
			default:
				System.out.println("Unknown ");
				break;				
			}
		}
		if(chart != null) {
			chart.addPoint(values[0], values[1], values[2]);
		}
	}
	
}

